package com.newasia.server.common.builder;

import com.alibaba.fastjson.JSONObject;
import lombok.Data;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class WeChatTokenApiBuilder {

    private TokenParam tokenParam = new TokenParam();

    public WeChatTokenApiBuilder addAppId(String name) {
        tokenParam.setAppId(name);
        return this;
    }

    public WeChatTokenApiBuilder addCode(String code) {
        tokenParam.setCode(code);
        return this;
    }

    public WeChatTokenApiBuilder addSecret(String secret) {
        tokenParam.setSecret(secret);
        return this;
    }

    public WeChatTokenApiBuilder addGrantType(String grantType) {
        tokenParam.setGrantType(grantType);
        return this;
    }

    public TokenParam build() {
        return this.tokenParam;
    }

    public WeChatInfoApiBuilder.UserInfoParam getAccessToken(TokenParam tokenParam){
        WeChatInfoApiBuilder.UserInfoParam param = new WeChatInfoApiBuilder().build();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?"
                + "appid=" + tokenParam.appId
                + "&secret=" + tokenParam.secret
                + "&code=" + tokenParam.code
                + "&grant_type=" + tokenParam.grantType;
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(url);
            URLConnection uc = urlObject.openConnection();
            uc.setRequestProperty("contentType", "UTF-8");
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(),"utf-8"));
            String inputLine = null;

            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
            param = JSONObject.parseObject(json.toString(),WeChatInfoApiBuilder.UserInfoParam.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return param;
    }

    @Data
    public class TokenParam {
        private String appId;
        private String secret;
        private String code;
        private String grantType;
    }


}
